package com.dkd.flow.context;
import com.alibaba.fastjson2.JSONObject;
import com.dkd.flow.domain.EProcessInstances;
import com.dkd.flow.domain.EProcessTask;
import com.dkd.flow.mapper.EProcessInstancesMapper;
import com.dkd.flow.mapper.EProcessTaskMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class ProcessContextBuilder {
    @Autowired
    private EProcessTaskMapper eProcessTaskMapper;
    @Autowired
    private EProcessInstancesMapper eProcessInstancesMapper;
    public ProcessContext build(JSONObject data) {
        ProcessContext context = new ProcessContext();
        EProcessInstances processInstances = new EProcessInstances();
        context.setFormValue(data.getJSONObject("formValue"));

        String processInstancesId = data.getString("processInstancesId");
        String taskId = data.getString("taskId");
        String processDefinitionId = data.getString("processDefinitionId");

        if (processInstancesId != null) {
            Long pid = Long.parseLong(processInstancesId);
            context.setProcessInstancesId(pid);
            processInstances = eProcessInstancesMapper.selectById(pid);
        }
        if (!taskId.isEmpty()) {
            Long curTaskId = Long.parseLong(taskId);
            context.setCurTaskId(curTaskId);
            EProcessTask curTask = eProcessTaskMapper.selectById(curTaskId);
            context.setCurTask(curTask);
            context.setCurTaskStatus(curTask.getTaskStatus());
        }
        if (processDefinitionId != null) {
            Long curProcessDefinitionId = Long.parseLong(processDefinitionId);
            context.setProcessDefinitionId(curProcessDefinitionId);
            processInstances.setProcessDefinitionId(curProcessDefinitionId);
        }
        processInstances.setFormValue(JSONObject.toJSONString(context.getFormValue()));
        context.setEProcessInstances(processInstances);
        return context;
    }
}


